import React, { useEffect, useLayoutEffect, useState } from 'react';
import { produce } from 'immer';
import { Button, Form, Input, Select, Space, Popconfirm, Tag, message, Image, TreeSelect } from 'antd';
import type { FormProps, TableColumnsType, PaginationProps } from 'antd';
import { getResourceList, updateResourcesStatus, getClassificationList } from "./../../api/resource"
import { resourceReqTypa, resourceResType, resourceResTypa, resourceReqStateType, classificationOpctionsType } from './../../types/resourceTypa';
import TableComponent from "./../../components/TableComponent";
import PaginationComponent from "./../../components/PaginationComponent";
import AddOrEdit from "./addOrEdit";
import styles from './index.module.scss';
import dayjs from 'dayjs';


const Resource: React.FC = () => {
  const [form] = Form.useForm();
  const [reqForm, setReqForm] = useState<resourceReqTypa>({
    resourcesId: undefined,
    categoryId: undefined,
    status: 0,
    keywords: "",
    paging: {
      page: 1,
      size: 10
    }
  });
  // 返回的数据
  const [data, setData] = useState<resourceResType>({
    count: 0,
    data: []
  });
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const [resourcesId, setResourcesId] = useState<number>();
  const [modalType, setModalType] = useState<'add' | 'edit'>('add');
  const [treeData, setTreeData] = useState<classificationOpctionsType[]>([]);

  // 设置选项内容
  const onFinish: FormProps<resourceReqTypa>['onFinish'] = (e) => {
    setReqForm(e);
  };
  // 获取数据
  const getDataList = () => {
    getResourceList(reqForm).then((res) => {
      if (res.code === 0) {
        setData(res.data)
      }
    });
  }
  // 分页切换
  const onChange: PaginationProps['onChange'] = (page, size) => {
    setReqForm(produce((draft) => {
      draft.paging = { page, size }
    }));
  };
  // 上下架
  const setResourceStatus = (e: resourceReqStateType) => {
    updateResourcesStatus(e).then((res) => {
      if (res.code === 0) {
        getDataList();
        message.success("修改成功");
      }
    })
  }
  // 数据初始化
  useLayoutEffect(() => {
    getClassificationList({
      sub: true,
      paging: {
        page: 1,
        size: 10000
      }
    }).then(res => {
      if (res.code === 0) {
        setTreeData(res.data.data)
      }
    })
  }, [])
  // 初始化加载
  useEffect(() => {
    getDataList()
  }, [reqForm])

  // 表格
  const columns: TableColumnsType<resourceResTypa> = [
    {
      title: '资源ID',
      dataIndex: 'resourcesId',
      key: 'resourcesId',
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '封面',
      dataIndex: 'coverImgUrl',
      key: 'coverImgUrl',
      render: (_, { coverImgUrl }) => {
        return (<Image
          width={100}
          height={50}
          src={coverImgUrl}
        />)
      }
    },
    {
      title: '资源详情',
      dataIndex: 'jumpType',
      key: 'jumpType',
      render: (_, { resourcesId }) => {
        return (<Button type='link' onClick={() => console.log(resourcesId)}>查看</Button>)
      }
    },
    {
      title: '分类',
      dataIndex: 'categoryId',
      key: 'categoryId',
    },
    {
      title: '发布时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (_, { createTime }) => {
        return dayjs.unix(createTime).format("YYYY-MM-DD hh:mm:ss")
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (_, { status }) => {
        if (status === 1) {
          return <Tag color='volcano' key={status}>
            上架
          </Tag>
        } else {
          return <Tag color='gold' key={status}>
            下架
          </Tag>
        }
      }
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      render: (_, { resourcesId, status }) => (
        <Space size="middle">
          <Button type="link" onClick={() => {
            setResourcesId(resourcesId);
            setIsModalOpen(true);
            setModalType('edit');
          }}>编辑</Button>
          <Popconfirm title={`确定${status === 1 ? '下' : '上'}架?`} onConfirm={() => { setResourceStatus({ resourcesId, status: status === 1 ? 2 : 1 }) }}>
            <Button type="link">{`${status === 1 ? '下' : '上'}架`}</Button>
          </Popconfirm>
        </Space>
      )
    },
  ];

  return (
    <div>
      <div className={styles.Hader}>
        <h2>资源管理</h2>
        <Form
          layout='inline'
          onFinish={onFinish}
          initialValues={reqForm}
          form={form}
        >
          <Form.Item<resourceReqTypa> name="keywords" style={{ width: 250 }} label="资源">
            <Input placeholder="请输入资源" />
          </Form.Item>
          <Form.Item<resourceReqTypa> name="resourcesId" style={{ width: 250 }} label="资源ID">
            <Input placeholder="请输入资源ID" />
          </Form.Item>
          <Form.Item<resourceReqTypa> name="categoryId" style={{ width: 250 }} label="分类">
           
            <TreeSelect fieldNames={{
              label: 'categoryName',
              value: "categoryId",
              children: "sub"
            }} treeData={treeData}  treeCheckable={true} placeholder="请选择分类"/>
          </Form.Item>
          <Form.Item<resourceReqTypa> name="status" style={{ width: 250 }} label="状态">
            <Select
              style={{ width: '100%' }}
              options={[{
                value: 0,
                label: "全部"
              }, {
                value: 1,
                label: "上架"
              }, {
                value: 2,
                label: "下架"
              }]}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType='submit'>查询</Button>
              <Button htmlType="reset" onClick={() => { form.resetFields() }}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
      <TableComponent<resourceResTypa> data={data.data} columns={columns}>
        <Space>
          <Button type="primary" onClick={() => {
            setIsModalOpen(true);
            setModalType('add')
          }}>添加</Button>
          <Button type="dashed" onClick={() => { }}>批量导入</Button>
        </Space>
      </TableComponent>
      <PaginationComponent count={data.count} onChange={onChange} />
      <AddOrEdit isModalOpen={isModalOpen} resourcesId={resourcesId} type={modalType} handleCancel={() => {
        setIsModalOpen(false);
        getDataList()
      }} />
    </div>
  );
};

export default Resource; 